/*
 * @Description:生成序号配置
 * @Author: Zzt
 * @Date: 2022-10-26 17:07:31
 * @LastEditTime: 2022-10-31 17:38:52
 */

import { useEffect, useState } from 'react';
import { Alert, Button, Checkbox, Form } from 'antd';
import classNames from 'classnames/bind';
import { fetchRepoListByType } from '@/api/archivesType';
import { isNullObj, jsonClone } from '@/utils';
import { selectItemByKey } from '@/utils/list';
import { useAutoIncreaseContext } from '../contexts/AutoIncreaseContext';
import type { IRepo } from '@/interfaces/archiveType';
import type { ITriggerMode } from '@/api/rulesettings/groupSortRule';
import styles from '../styles/panes.module.scss';

const cx = classNames.bind(styles);

type ITriggerForm = ITriggerMode<number>;

const BuildConfiguration = () => {
  const { selectAT, commonRule, saveGroupSortRuleFunc } = useAutoIncreaseContext();

  const [form] = Form.useForm();

  const [dbList, setDbList] = useState<IRepo[]>([]);

  useEffect(() => {
    if (selectAT?.id) {
      const { id, atType } = selectAT;
      fetchRepoListByType(atType, id).then((res) => {
        const data: IRepo[] = res.data;
        if (data?.length > 0) {
          setDbList(
            data.map((repo) => {
              delete repo.createStatus;
              return repo;
            })
          );
        }
      });
    }
  }, [selectAT]);

  useEffect(() => {
    if (commonRule && commonRule.triggerMode && !isNullObj(commonRule.triggerMode)) {
      const triggerMode: ITriggerMode = commonRule.triggerMode;
      const triggerForm: ITriggerForm = {
        ...triggerMode,
        dbList: triggerMode.dbList ? triggerMode.dbList.map((repo) => repo.id) : []
      };
      form.setFieldsValue(triggerForm);
    }
  }, [commonRule]);

  /**
   * @description: 提交表单，触发表单提交事件
   */
  const submitFunc = () => {
    form.submit();
  };

  const onFinish = (values: ITriggerForm) => {
    const copyVal: ITriggerForm = jsonClone(values);
    const triggerMode: ITriggerMode = {
      ...copyVal,
      dbList: copyVal.dbList.map((repoId) => selectItemByKey(repoId, dbList))
    };
    console.log({ values, triggerMode });
    saveGroupSortRuleFunc({ ...commonRule, triggerMode });
  };

  return (
    <div className={cx('auto-filing--container')}>
      <div className={cx('tips')}>
        <Alert
          description="为了给档案人员的录入工作提供方便，利用流水号自增功能可以设置某个字段按照设置的规则自动增长。
      默认长度是用来控制自增字段的形式，设置默认长度为3。分组长度是控制自增字段累加的规则，相同的分组条件下才开始计算组内自增。"
          type="info"
          showIcon
          closable
        />
      </div>
      <div className={cx('tabs-wrap')}>
        <div className={cx('filing-pane')}>
          <div className={cx('filing-header')}>
            <div className={cx('title')}>序号生成方式的配置</div>
            <div className={cx('operate')}>
              <Button onClick={submitFunc}>保存</Button>
            </div>
          </div>
          <div>
            <Form
              form={form}
              labelAlign="left"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
              colon={false}
              labelWrap
              onFinish={onFinish}
            >
              <Form.Item label="按系统规则生成序号">
                <Form.Item
                  label="触发方式"
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 23, offset: 1 }}
                  className={cx('build-form')}
                >
                  <Form.Item
                    name="autoTrigger"
                    extra="说明：在条目创建和序号规则内相关字段修改时，系统自动生成序号"
                    valuePropName="checked"
                  >
                    <Checkbox>自动触发（建议）</Checkbox>
                  </Form.Item>
                  <Form.Item
                    name="manualTrigger"
                    extra="说明：用户选择条目，手动执行按规则生成序号"
                    valuePropName="checked"
                  >
                    <Checkbox>手动触发</Checkbox>
                  </Form.Item>
                </Form.Item>
                <Form.Item
                  label="序号不重复范围"
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 23, offset: 1 }}
                  className={cx('build-form')}
                >
                  <Form.Item
                    name="dbList"
                    extra="说明：在按规则生成序号时，系统检测所设置范围内的所有分组条目，以确保序号的唯一性"
                  >
                    <Checkbox.Group
                      options={dbList.map((repo) => ({
                        label: repo.description,
                        value: repo.id
                      }))}
                    />
                  </Form.Item>
                </Form.Item>
              </Form.Item>
              <Form.Item label="手动输入序号">
                <Form.Item
                  name="manualInput"
                  extra="说明：用户可以在著录卡片内手动输入序号“值”"
                  wrapperCol={{ span: 23, offset: 1 }}
                  className={cx('build-form')}
                  valuePropName="checked"
                >
                  <Checkbox>手动输入</Checkbox>
                </Form.Item>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};
export default BuildConfiguration;
